package com.study.www.web;

import com.study.www.config.IdWorks;
import com.study.www.config.Result;
import com.study.www.config.WebLog;
import com.study.www.test1.entity.Dept;
import com.study.www.test1.entity.User;
import com.study.www.test1.entity.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController()
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    UserRepository userRepository;

    @WebLog("用户查询")
    @GetMapping(value = {"/{id}", ""})
    public Result get(@PathVariable(required = false) String id) {
        if (StringUtils.isBlank(id)) {
            List<User> all = userRepository.findAll();
            return Result.success(all);
        } else {
            return Result.success(userRepository.findById(id));
        }
    }

    @WebLog("用户新增")
    @PostMapping(value = "")
    @Transactional
    public Result saveUser(@RequestBody User user) {
        user.setId(IdWorks.getId());
        user.setRegisterTime(new Date());
        userRepository.save(user);
        return  Result.success();
    }
}
